package com.eliauk.democommon.utils.page;

import com.eliauk.democommon.dto.PageData;
import com.eliauk.democommon.query.PageQuery;

import java.util.List;

public class PageUtil {

    private static final int DEFAULT_PAGE_SIZE = 10;

    /**
     * @param list     分页前的集合
     * @param currPage  页码
     * @param pageSize 页数
     * @param <T>
     * @return 分页后的集合
     */
    public static <T> PageData<T> pageList(List<T> list, int currPage, int pageSize) {
        //计算总页数
        int page = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
        //兼容性分页参数错误
        currPage = currPage <= 0 ? 1 : currPage;
        currPage = currPage >= page ? page : currPage;
        // 开始索引
        int begin = 0;
        // 结束索引
        int end = 0;
        if (currPage != page) {
            begin = (currPage - 1) * pageSize;
            end = begin + pageSize;
        } else {
            begin = (currPage - 1) * pageSize;
            end = list.size();
        }
        int total = list.size();
        list = list.subList(begin, end);

        return new PageData<>(list, Long.valueOf(total), Long.valueOf(page));
    }

    public static <T, Q extends PageQuery> List<T> pageList(List<T> list, Q query) {
        int pageSize = query.getPageSize();
        int currPage = query.getCurrPage();

        // 计算总页数
        int totalPages = (int) Math.ceil((double) list.size() / pageSize);

        // 校正当前页数
        currPage = Math.max(1, Math.min(currPage, totalPages));

        // 计算开始和结束索引
        int begin = (currPage - 1) * pageSize;
        int end = Math.min(begin + pageSize, list.size());

        return list.subList(begin, end);
    }
}
